﻿using System;
using System.Collections.Generic;
using Algoritmia.Utils;
using Lists = Algoritmia.DataStructures.Lists;
using System.Linq;

namespace Algoritmia.Problems.BinPacking
{
    public class FirstFitBinPacker : IBinPacker
    {
        private readonly Func<Lists.IList<double>> _createList;

        public FirstFitBinPacker(Func<Lists.IList<double>> createList = null)
        {
            _createList = createList ?? (() => AlgoritmiaFactory.Lists<double>.Default);
        }

        #region Implementation of IBinPacker

        public IEnumerable<int> Pack(Lists.IList<double> items, double capacity)
        {
            var indices = Enumerable.Repeat(-1,items.Count).ToArray();
            var free = _createList();
            for(int i = 0; i < items.Count; i++)
            {
                for(int j = 0; j < free.Count; j++)
                {
                    if ( free[j] >= items[i])
                    {
                        indices[i] = j;
                        free[j] -= items[i];
                        break;
                    }
                }
                if ( indices[i] == -1)
                {
                    indices[i] = free.Count;
                    free.Add(capacity - items[i]);
                }
            }
            return indices;
        }

        #endregion
    }
}
